import React from 'react';
import moment from 'moment';
import _ from 'lodash';
import { Radio, DatePicker, Select } from 'antd';

const RadioGroup = Radio.Group;
const RadioButon = Radio.Button;
const Option = Select.Option;
const MouthPicker = DatePicker.MonthPicker;

moment.locale('zh-cn');

export default (props) => {
    const {
        type,
        value,
        onChange = v => v,
        beforeYears = 5,
    } = props;
    const changeQuery = (e) => {
        const type = e.target.value;
        let value;
        if (type === 'month') {
            value = moment().format('YYYY-MM');
        } else if (type === 'year') {
            value = moment().format('YYYY');
        }
        if (_.isFunction(onChange)) {
            onChange({ type, date: value });
        }
    };
    const picker = (type) => {
        const onChangeDate = (type, value) => {
            if (_.isObject(value)) {
                value = value.format('YYYY-MM');
            }
            if (_.isFunction(onChange)) {
                onChange({ type, date: value });
            }
        };
        switch (type) {
            case 'month': {
                return (
                    <MouthPicker
                        onChange={onChangeDate.bind(null, type)}
                        defaultValue={moment(value)}
                        allowClear={false}
                    />
                );
            }
            case 'year': {
                const year = moment().year();
                const options = (before = beforeYears) => {
                    let curYear = year;
                    const res = [];
                    while (before > 0) {
                        res.push(<Option key={year} value={curYear.toString()}>{curYear}</Option>);
                        before--;
                        curYear--;
                    }
                    return res;
                };
                return (
                    <Select
                        defaultValue={year.toString()}
                        onChange={onChangeDate.bind(null, type)}
                    >
                        {options()}
                    </Select>
                );
            }
        }
    };

    return (
        <div>
            <RadioGroup onChange={changeQuery} value={type}>
                <RadioButon value="month">月度</RadioButon>
                <RadioButon value="year">年度</RadioButon>
            </RadioGroup>
            {picker(type)}
        </div>
    );
};
